package Queue;

public class MyQueue {
    //以双向链表来实现，尾部为队，头部为队头
    static class ListNode{
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode first;
    public ListNode last;
    public int usedSize = 0;



    public void offer(int val){
        ListNode node = new ListNode(val);
        if(isEmpty()){
            first = last = node;
        }else {
            last.next = node;
            node.prev = last;
            last = last.next;
        }
        this.usedSize++;
    }

    public int poll(){
        if (isEmpty()){
            return -1;
        }

        int popVal = first.val;
        first = first.next;
//        if (usedSize != 1){
//            first.prev = null;
//        }
        //当队列中只剩一个元素的时候再用头删法移动，直接first被置空了，所以first.prev就不能再去修改置空
        //所以判断一下，只要first不是空就可以执行，将first.prev置空
        if(first != null){
            first.prev = null;
        }
        usedSize--;
        return popVal;
    }

    public int peek(){
        if (isEmpty()){
            return -1;
        }
        return first.val;
    }


    public boolean isEmpty(){
        return usedSize == 0;
        //return first == null;
    }

}
